package com.yuyu.helper;

import com.yuyu.annotation.RequestMapping;
import com.yuyu.bean.Handler;
import com.yuyu.bean.Request;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 助手类工具类
 * author:yuyu
 * Date:2018/10/20
 * Time:23:59
 */
public final class ControlerHelper {

    /**
     * 用于存放请求与处理器的映射关系
     */
    private static final Map<Request,Handler> REQUEST_HANDLER_MAP = new HashMap<Request, Handler>();



    static {
        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
        if (CollectionUtils.isNotEmpty(controllerClassSet)){
            for (Class<?> controllerClass:controllerClassSet){
                Method[] methods = controllerClass.getDeclaredMethods();
                if (ArrayUtils.isNotEmpty(methods)){
                    for (Method method:methods){
                        if (method.isAnnotationPresent(RequestMapping.class)){
                            RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                            String mapping = requestMapping.value();
                            // \w	匹配包括下划线的任何单词字符。等价于“[A-Za-z0-9_]”
                            if (mapping.matches("\\w+:/\\w*")){
                                String[] array = mapping.split(":");
                                if(ArrayUtils.isNotEmpty(array)&& array.length == 2){
                                    String requestMethod = array[0];
                                    String requestPath = array[1];
                                    Request request = new Request(requestMethod,requestPath);
                                    Handler handler = new Handler(controllerClass,method);

                                    REQUEST_HANDLER_MAP.put(request,handler);
                                }
                            }


                        }
                    }
                }
            }
        }
    }

    /**
     * 获取Handler
     * @param requestMethod
     * @param requestPath
     * @return
     */
    public static Handler getHandler(String requestMethod,String requestPath){
        Request request = new Request(requestMethod, requestPath);
        return REQUEST_HANDLER_MAP.get(request);
    }
}